﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithm.Easy_1984_MinimumDifference
{
    class MainProject
    {
        static void Main(string[] args)
        {
            int s = MinimumDifference(new int[] { 87063, 61094, 44530, 21297, 95857, 93551, 9918 }, 6);
            Console.WriteLine(s);

            Console.ReadKey();
        }
        public static int MinimumDifference(int[] nums, int k)
        {
            //排序+双指针
            if (k == 1) return 0;

            Array.Sort(nums);

            int firstIndex = 0;
            int SecondIndex = firstIndex + k - 1;

            int minValue = int.MaxValue;

            int res = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                res = Math.Abs(nums[firstIndex] - nums[SecondIndex]);
                if (minValue > res)
                    minValue = res;
                firstIndex++;
                SecondIndex++;
                if (SecondIndex >= nums.Length) break;

            }
            return minValue;
            //return 0;
        }
    }
}
